#-*- coding:utf-8 -*-

import wx
import time
import baseUI
import my_verson
import urllib3
import requests
import winsound
import re
import lodcfg
import paho.mqtt.client as mqtt
import  json

# from SRC_Config import configset

class MainDialog(baseUI.MyDialog1):

    def __init__(self):
        baseUI.MyDialog1.__init__(self,None)
        self.project = False
        self.startMqtt()

    def m_button1OnButtonClick(self,event):
        self.product = self.m_choice1.GetString(self.m_choice1.GetSelection())
        self.project = self.m_comboBox2.GetValue().lower()
        self.testTime = int(self.m_textCtrl7.GetValue())
        self.email = self.m_textCtrl6.GetValue()

        mesg = "%s_%s_email_%s_time_%d"%(self.product,self.project,self.email,self.testTime)
        print(mesg)
        self.on_publish("airm2m/publish",mesg , 1)
        self.appendToShow("已经发布,等待测试服务器返回状态")

    def appendToShow(self,mesg):
        self.m_textCtrl61.AppendText("%s:%s\r\n"%(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())),mesg))
        pass

    def on_publish(self,topic,mes,qos):
        self.mqttClient.publish(topic, mes, qos)


    def on_message_come(self,lient, userdata, msg):
        print(msg.topic, msg.payload)
        if msg.topic == "airm2m/testInfoat" or msg.topic == "airm2m/testInfolua" or msg.topic == "airm2m/testInfocsdk"  :
            projectMatch = re.match("airm2m/testInfo(.*)", msg.topic)
            if projectMatch:
                if projectMatch.group(1) == self.project:
                    self.appendToShow(str(msg.payload, encoding = 'gbk'))


    def on_subscribe(self):
        self.mqttClient.subscribe("airm2m/testInfoat", 1)
        self.mqttClient.subscribe("airm2m/testInfolua", 1)
        self.mqttClient.subscribe("airm2m/testInfocsdk", 1)
        self.mqttClient.on_message = self.on_message_come

    def startMqtt(self):
        MQTTHOST = "192.168.39.233"
        MQTTPORT = 1883
        self.mqttClient = mqtt.Client()
        self.mqttClient.connect(MQTTHOST, MQTTPORT, 60)
        self.mqttClient.loop_start()
        self.on_subscribe()
        pass


    def OnClose(self,event):
        self.Destroy()
        event.Skip()
def main():
    app =wx.App()
    dialog = MainDialog()
    name = my_verson.myproject["Title"] + " "+ my_verson.myproject["Verson"]
    dialog.SetTitle(name)
    dialog.Show(True)
    app.MainLoop()

if __name__ == "__main__":
    main()
